﻿var business = business ||
    {
        getEnvironmentNodes: window.prefixURL + "BusinessTopology/GetEnvironmentNodes",
        getTreeNodesURL: window.prefixURL + "BusinessTopology/GetTreeNodes",
        getVirtualHostByIdURL: window.prefixURL + "BusinessTopology/GetVirtualHostsByAppId",
        searchVirtualHostsURL: window.prefixURL + "BusinessTopology/SearchVirtualHosts",
        getVirtualHostById: window.prefixURL + "BusinessTopology/GetVirtualHostById",



        bodyTpl: _.template($("#listTemplate").html()),
        pagerTpl: _.template($("#pagingTablePager").html()),

        pageIndex: function () {
            return $("#nav").find("li[flag]").find("a").html();
        },

        pageSize: function () {
            return $("#nav").find(".pagingTablePageCountSelect").val();
        },

        OnClick: function (event, treeId, treeNode) {
            business.nodeClick(treeNode);
        },

        OnBeforeExpand: function (treeId, treeNode) {
            business.nodeClick(treeNode);
        },

        nodeClick: function (treeNode) {
            var t = this;
            $("#txtSearchAppId").val("");

            if (treeNode.open === false) {

                var parentId = treeNode.id;
                var level = treeNode.level;
                var bakValue = treeNode.bakValue;

                if (level < 2) {
                    $.ajax({
                        url: "/BusinessTopology/GetTreeNodes?level=" + level + "&parentId=" + parentId + "&bakValue=" + bakValue,
                        type: "GET",
                        dataType: "Json",
                        success: function (data) {
                            if (data.businessCode !== -1) {
                                var zTree = $.fn.zTree.getZTreeObj("ztree");
                                zTree.removeChildNodes(treeNode);
                                zTree.addNodes(treeNode, data.returnObj);
                            } else
                                alert(data.businessMessage);
                        },
                        error: function (data) {
                            alert("error:" + data);
                        }
                    });
                } else {

                    $("#txtSearchAppId").val(bakValue);
                    t.search(1);
                }
            } else {
                var treeObj = $.fn.zTree.getZTreeObj("ztree");
                treeObj.expandNode(treeNode, false, true, true);
            }
        },

        scrollDiv: function () {
            var windowHeight = $(window).height();
            var footerHeight = $(".main-footer").outerHeight() || 0;
            var neg = $(".main-header").outerHeight() + footerHeight + 30;
            $("#topoPanel").css("height", windowHeight - neg);
        },

        getTreeNodes: function (level, parentId) {
            var t = this;
            var setting = {
                view: {
                    selectedMulti: false
                },
                edit: {
                    enable: true,
                    showRemoveBtn: false,
                    showRenameBtn: false
                },
                data: {
                    keep: {
                        parent: true,
                        leaf: true
                    },
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    beforeExpand: t.OnBeforeExpand,
                    onClick: t.OnClick
                }
            };

            var url = t.getTreeNodesURL + "?level=" + level + "&parentId=" + parentId;
            $.ajax({
                url: url,
                type: "GET",
                dataType: "Json",
                success: function (data) {
                    if (data.businessCode !== -1) {
                        $.fn.zTree.init($("#ztree"), setting, data.returnObj);
                    } else
                        alert(data.businessMessage);
                },
                error: function (data) {

                }
            });
        },

        del: function (sender, id) {
            var returnVal = confirm("Are you sure？");
            if (returnVal === false) {
                return;
            } else {
                $.ajax({
                    url: sender.delBusinessInfo + "?id=" + id,
                    type: "GET",
                    dataType: "Json",
                    success: function (data) {
                        if (data.returnObj === true) {
                            alert("Success！");
                            sender.getList(1);
                        } else {
                            alert("Error:" + data.businessMessage);
                        }
                    }
                });
            }
        },

        edit: function (sender, id) {
            $.ajax({
                url: sender.getBusinessInfo + "?id=" + id,
                type: "GET",
                dataType: "Json",
                success: function (data) {
                    if (data.businessMessage !== -1) {
                        $("#txtBusinessId").val(data.returnObj.id);
                        $("#txtName").val(data.returnObj.name);
                        $("#txtDecription").val(data.returnObj.description);
                        $("#txtPIC").val(data.returnObj.picName);
                        $("#selectEnvs").val(data.returnObj.environmentId)
                        $("#createModel").modal();
                    } else {
                        alert(data.businessMessage);
                    }
                },
                error: function (data) {
                    alert("Error:" + data);
                }
            });
        },

        search: function (pageIndex) {
            var t = this;
            var appId = $("#txtSearchAppId").val();
            if (appId === "") {
                alert("请先选中对应的应用程序！");
                return;
            }

            var innerIP = $("#search-innerIP").val();
            var outerIP = $("#search-outerIP").val();
            var os = $("#search-os").val();
            var status = $("#search-status").val();


            var url = t.searchVirtualHostsURL + "?innerIP=" + innerIP
                + "&outerIP=" + outerIP
                + "&os=" + os
                + "&status=" + status
                + "&applicationId=" + appId
                + "&pageIndex=" + pageIndex
                + "&pageSize=10";

            $.ajax({
                url: url,
                type: "GET",
                success: function (data) {
                    if (data.businessCode != -1) {
                        $("#tbody").html(t.bodyTpl(data.returnObj));
                        $("#nav").html(t.pagerTpl(data.pager));
                        $(".pagingTablePageCountSelect").val(data.pager.PageSize);
                    } else
                        alert(data.businessMessage);
                },
                error: function (data) {
                    alert("error:" + data);
                }
            });
        },

        initPage: function () {
            var t = this;
            setTimeout(function () {
                t.scrollDiv();
            },
                0);

            t.getTreeNodes(0, 0);
        },

        bindEvents: function () {
            var t = this;

            $(window).resize(function () {
                t.scrollDiv();
            });

            $("span[name='opt-create']").bind("click",
                function () {
                    //$("#").val("");
                    $("#txtName").val("");
                    $("#txtDecription").val("");
                    $("#selectEnvs").val("");
                    $("#txtPIC").val("");

                    $("#crtHeader").html("Create Business");
                    $("#createModel").modal();
                });

            $("#tbody").delegate("tr td span",
                "click",
                function () {
                    var type = $(this).data("type");
                    var id = $(this).data("id");
                    if (type === "edit") {
                        t.edit(t, id);
                    } else {
                        t.del(t, id);
                    }
                });

            $("#btnSubmit").bind("click",
                function () {

                    var $btn = $(this).button("loading...");
                    var id = $("#txtBusinessId").val();
                    var name = $("#txtName").val();
                    var description = $("#txtDecription").val();
                    var env = $("#selectEnvs").val();
                    var pic = $("#txtPIC").val();

                    $.ajax({
                        url: t.addOrUpdateBusinessInfo,
                        type: "POST",
                        dataType: "Json",
                        data: {
                            Id: id,
                            Name: name,
                            Description: description,
                            EnvironmentId: env,
                            PICName: pic
                        },
                        success: function (data) {
                            if (data.returnObj === true) {
                                $("#createModel").modal("hide");
                                $btn.button("reset");
                                t.getList(1);
                            } else {
                                $("#createErrorMsg").show().children("div").find("span").html(data.businessMessage);
                                $btn.button("reset");
                            }
                        },
                        error: function (event) {
                            alert("Error:" + event);
                        }
                    });
                });

            $("#nav").delegate("ul li:not('.disabled')",
                "click",
                function () {
                    var arialabel = $(this).children("a").attr("aria-label");
                    var pageIndex = $(this).children("a").attr("data-page");
                    var activePageIndex = t.pageIndex();
                    if (arialabel != undefined) {
                        if (arialabel === "Previous") {
                            t.search(parseInt(activePageIndex) - 1);
                        } else if (arialabel === "Next") {
                            t.search(parseInt(activePageIndex) + 1);
                        }
                    } else {
                        t.search(pageIndex);
                    }
                });

            $(".topoleft-icon").bind("click",
                function () {

                    if ($(".glyphicon").hasClass("glyphicon-menu-left")) {
                        $(".topoLeft").animate({ "width": "0px" }, "fast");
                        $(".topoRight").animate({ "marginLeft": "30px" }, "fast");
                        $(".glyphicon").removeClass("glyphicon-menu-left").addClass("glyphicon-menu-right");
                        $(".ztree").hide();
                    } else {
                        $(".topoLeft").animate({ "width": "320px" }, "fast");
                        $(".topoRight").animate({ "marginLeft": "350px" }, "fast");
                        $(".glyphicon").removeClass("glyphicon-menu-right").addClass("glyphicon-menu-left");
                        $(".ztree").show();
                    }
                });

            $("#showSearch").bind("click", function () {
                if ($(this).hasClass("fa-angle-down")) {
                    $(this).removeClass("fa-angle-down").addClass("fa-angle-up");

                    $("#topoRight-search").animate({ "height": "160px" }, "fast");
                    $(".topoRight-condition").show();
                } else {
                    $(this).removeClass("fa-angle-down").addClass("fa-angle-down");

                    $("#topoRight-search").animate({ "height": "0px" }, "fast");
                    $(".topoRight-condition").hide();
                }
            });

            $("#search-clear").bind("click", function () {
                $("#search-innerIP").val("");
                $("#search-outerIP").val("");
                $("#search-os").val("");
                $("#search-status").val("");
            });

            $("#search-submit").bind("click", function () {
                t.search(1);
            });

            $("#tbody").delegate("tr", "dblclick", function (sender) {
                var id = $(this).data("id");
                $.ajax({
                    url: t.getVirtualHostById + "?id=" + id,
                    type: "GET",
                    success: function (data) {
                        if (data.businessCode !== -1) {
                            var obj = data.returnObj;
                            $("#d-id").html(obj.id);
                            $("#d-assetId").html(obj.assetId);
                            $("#d-area").html(obj.area);
                            $("#d-deviceType").html(obj.deviceTypeName);
                            $("#d-os").html(obj.osName);
                            $("#d-osVersion").html(obj.osVersion);
                            $("#d-adminName").html(obj.adminName);
                            $("#d-password").html(obj.password);
                            $("#d-innerIP").html(obj.innerIP);
                            $("#d-outerIP").html(obj.outerIP);
                            $("#d-cpu").html(obj.cpu + "核");
                            $("#d-hardDiskSize").html(obj.hardDiskSize + "GB");
                            $("#d-ram").html(obj.ram + "GB");
                            $("#d-maintainers").html(obj.maintainers);
                            $("#d-status").html(obj.statusName);
                            $("#d-createTime").html(obj.createTime);
                            $("#d-expiredTime").html(obj.expiredTime);
                            $("#d-remark").html(obj.remark);

                            $("#details").modal();
                        }
                        else
                            alert(data.businessMessage);
                    },
                    error: function (data) {
                        alert("error:" + data);
                    }
                });
            });

            $("#check-all ").bind("change", function () {
                var chk = $(this).prop("checked");
                $("#tbody input[type='checkbox']").prop("checked", chk);
            });

            $(".topoRight-option span").bind("click", function (sender) {
                alert(this.innerText);
            });
        },

        //@入口方法
        init: function () {
            var t = this;
            t.bindEvents();
            t.initPage();
        }
    };

business.init();
